<?php

class Pay extends CComponent{
	
	
	/**
	 * 调试
	 */
	public $debug = false;
	
	/**
	 * 
	 * 保存支付接口信息的model名
	 * @var string
	 */
	public $paymentModel;
	
	/**
	 * 
	 * 支付接口对象容器
	 * @var array
	 */
	protected $_payMent = array();
	
	/**
	 * 
	 * 当前支付接口对象
	 * @var object
	 */
	protected $_current;
	
	/**
	 * 
	 * 支付接口的配置
	 * 在config中配置
	 * 支付密码等信息也可保存在model中
	 * 如果配置文件和model中同时存在接口信息，优先使用model
	 * @var array
	 */
	public $handler = array();
	
	/**
	 * 初始化
	 * Enter description here ...
	 */
	public function init() {
		foreach ($this->handler as $k=>$v){
			$this->_payMent[$k] = Yii::createComponent($this->initPayMentData($k,$v));
		}
	}
	
	/**
	 * 
	 * 初始化支付接口信息
	 * @param string 支付接口英文标识
	 * @param array 支付接口配置信息
	 */
	public function initPayMentData($name,$config){
		if(!empty($this->paymentModel)){
			$model = new $this->paymentModel;
			$payment = $model->findByAttributes(array('type'=>$name));
			if(is_object($payment)){
				$config['paymentId'] = $payment->pay_id;
				$config['paymentKey'] = $payment->pay_key;
				$config['paymentAccount'] = $payment->pay_account;
			}
		}
		return $config;
	}
	
	protected function setPayMent($name = null){
		return in_array($name, array_keys($this->_payMent)) ? $this->_current = $this->_payMent[$name] : false;
	}
	
	public function __get($name){
		return is_object($this->setPayMent($name)) ? $this : parent::__get($name);
	}
	
	/**
	 * 
	 * 支付
	 * @param string $goodsName
	 * @param float $price
	 */
	public function toPay($goodsName,$price){
		$price = $this->debug ? 0.01 : $price;
		return is_object($this->_current) ? $this->_current->pay($this->tid,$goodsName,$price) : false;
	}
	
	public function getTid(){
		return is_object($this->_current) ? $this->_current->tid : false;
	}
	
	public function getPrice(){
		return is_object($this->_current) ? $this->_current->price : false;
	}
	
	public function getNotify(){
		return is_object($this->_current) ? $this->_current->notify : false;
	}
	
}